import Mock from 'mockjs'
import type { IUserList } from '../types/user'
// get请求从config.url获取参数，post请求从req.body获取参数
const param2obj = (url: string) => {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

// 生成200条数据
const List: IUserList[] = []
const count = 200
for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock('@county(true)'),
      'age|18-60': 1,
      birthday: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1)
      // email: '@email',
      // phone: /^1[34578]\d{9}$/,
      // address: '@county(true)',
      // 'gender|1': [0, 1],
      // createTime: '@datetime',
      // updateTime: '@datetime'
    })
  )
}

export default {
  getUserList: (config: any) => {
    const { name, page = 1, limit = 10 } = param2obj(config.url)
    // 如果有name参数，则模糊查询
    const mockList = List.filter((user) => {
      if (name && user.name.indexOf(name) === -1) return false
      return true
    })
    // 分页
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 200,
      data: {
        list: pageList,
        count: mockList.length
      }
    }
  },
  // 删除用户
  deleteUser: (config: any) => {
    const { id } = param2obj(config.url)
    const index = List.findIndex((user) => user.id === id)
    if (index !== -1) {
      List.splice(index, 1)
      return {
        code: 200,
        message: '删除成功'
      }
    } else {
      return {
        code: 500,
        message: '删除失败，用户不存在'
      }
    }
  },
  // 新增用户
  addUser: (config: any) => {
    const { name, addr, age, birthday, sex } = JSON.parse(config.body)
    const newUser = {
      id: Mock.Random.guid(),
      name,
      addr,
      age,
      birthday,
      sex
    }
    List.unshift(newUser)
    return {
      code: 200,
      message: '新增成功',
      data: newUser
    }
  },
  // 更新用户
  updateUser: (config: any) => {
    const { id, name, addr, age, birthday, sex } = JSON.parse(config.body)
    const index = List.findIndex((user) => user.id === id)
    if (index !== -1) {
      List[index].name = name
      List[index].addr = addr
      List[index].age = age
      List[index].birthday = birthday
      List[index].sex = sex
      return {
        code: 200,
        message: '更新成功',
        data: List[index]
      }
    } else {
      return {
        code: 500,
        message: '更新失败，用户不存在'
      }
    }
  },
  // 用户登录有关
  loginGetMenu: (config: any) => {
    const { username, password } = JSON.parse(config.body)
    if (username === 'admin' && password === 'admin123') {
      return {
        code: 200,
        data: {
          menuList: [
            {
              path: '/home',
              name: 'home',
              label: '首页',
              icon: 'house',
              url: 'MainView'
            },
            {
              path: '/mall',
              name: 'mall',
              label: '商品管理',
              icon: 'video-play',
              url: 'MallView'
            },
            {
              path: '/user',
              name: 'user',
              label: '用户管理',
              icon: 'user',
              url: 'UserView'
            },
            {
              path: '/other',
              label: '其他',
              icon: 'location',
              children: [
                {
                  path: '/other/order',
                  name: 'order',
                  label: '订单管理',
                  icon: 'tickets',
                  url: 'OrderView'
                },
                {
                  path: '/other/page',
                  name: 'page',
                  label: '页面管理',
                  icon: 'document',
                  url: 'PageView'
                }
              ]
            }
          ],
          token: Mock.Random.guid(),
          message: 'admin登录成功'
        }
      }
    } else if (username === 'user' && password === 'user123') {
      return {
        code: 200,
        data: {
          menuList: [
            {
              path: '/home',
              name: 'home',
              label: '首页',
              icon: 'house',
              url: 'MainView'
            },

            {
              path: '/user',
              name: 'user',
              label: '用户管理',
              icon: 'user',
              url: 'UserView'
            }
          ],
          token: Mock.Random.guid(),
          message: 'user登录成功'
        }
      }
    } else {
      return {
        code: 401,
        data: {
          message: '用户名或密码错误'
        }
      }
    }
  }
}
